package com.bankfourfactor.youdun;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alipay.api.internal.util.StringUtils;
import com.bankfourfactor.BankCarFactorEntity;
import com.bankfourfactor.BankCarFactoryConstant;
import com.bankfourfactor.RetCodeEnum;
import com.bankfourfactor.nanyun.NanYunFourFactor;
import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.dto.ResultInfo;
import com.seek.model.entity.TBaseBanktype;
import com.seek.service.CustomerCardService;
import com.seek.util.BankUtil;
import com.seek.util.DateUtil;

import net.sf.json.JSONObject;

public class YouDunFourFactor {
	 private static Logger logger = LoggerFactory.getLogger(YouDunFourFactor.class); 
	private static  CustomerCardService  customerCardService =  (CustomerCardService)SpringContextHolder.getBean("customerCardService");
	
	public static ResultInfo submitYouDunFactor(BankCarFactorEntity b) throws Exception{
		ResultInfo result = new ResultInfo();
		String status = "";
		String message = "";
		String orderNo = "";
		String orgName = "";
		if(null!=b){
			Map repMap = new HashMap();
			Map<String,String> data = new HashMap<String,String>();
			data.put("id_name",new String(b.getIdName().getBytes(),"Utf-8"));
			data.put("bank_card_no",b.getCardNo());
			data.put("id_no",b.getIdNo());
			data.put("mobile",b.getPhone());
			data.put("req_type",BankCarFactoryConstant.YOUDUN_REQ_TYPE);
			String resJson = "";
			try {
				logger.error(JSON.toJSONString(data)+"zhizhizhzihzizhizhzihzizhizhzihzizhizhzih");
				resJson  = PartnerRequest.apiCall(BankCarFactoryConstant.YOUDUN_URL,BankCarFactoryConstant.PUBLIC_KEY_ONLINE, BankCarFactoryConstant.BUSINESS_PRIVATE_KEY,BankCarFactoryConstant.YOUDUN_PRODUCT_CODE,b.getSeq(), data);
			} catch (Exception e) {
				//这种情况是属于网络不通
				resJson = "{header: {ret_code: 99999}}";
			}
			JSONObject json = JSONObject.fromObject(resJson);
			System.out.println(json.toString()+"=========json.toString()===========");
			String retcode= JSONObject.fromObject(json.getString("header")).getString("ret_code");
			if("000000".equals(retcode)){
				JSONObject body = json.getJSONObject("body");
				//有盾接口对接成功
				 String udOrderNo= JSONObject.fromObject(json.getString("body")).getString("ud_order_no");//有盾返回的交易号，楠云是没有的
				 status = JSONObject.fromObject(json.getString("body")).getString("status");
				 message = JSONObject.fromObject(json.getString("body")).getString("message");//认证信息
				 orderNo = JSONObject.fromObject(json.getString("body")).getString("ud_order_no");
				 orgName = JSONObject.fromObject(json.getString("body")).getString("org_name");//返回的银行卡名称
				 //认证状态,并通过枚举进行数据转换,放入实体对象中
				 result.setStatus(new Integer(RetCodeEnum.getRetCodeEnumByValue("ud",status).getDesc()));
				 result.setMessage(message);
				 repMap.put("orgCode", "YOUDUN");
				//修改有盾的第三方接口调用记录表(0:失败，1：成功)
				 repMap.put("udtype","1");
			}else{//有盾接口对接失败
				//对接失败，掉起楠云进行对接
				//修改有盾的第三方接口调用记录表(0:失败，1：成功)
				repMap.put("udtype","0");
				try {
					 orgName = BankUtil.getNameOfBank(b.getCardNo());
					if(StringUtils.isEmpty(orgName)){
						 result.setStatus(1);
						 result.setMessage("暂时不支持该银行卡，请换卡！！！");
						 repMap.put("nytype","0");//设置为调用失败（没调用）
						 repMap.put("history", 1);
					}else{
				     	Map map = NanYunFourFactor.submitNanYunFactor(b);
					    repMap.put("nytype","1");
						if(map==null||map.keySet().size()<=0){
							 result.setStatus(1);
							 result.setMessage("认证异常，请告知客服，稍后再试！！！");
						}else{
							 JSONObject nyjson = JSONObject.fromObject(map);
							 status = nyjson.getString("result").equals("0")?"0":"1";//认证状态
							 message = nyjson.getString("respMsg");//认证信息
							 result.setStatus(new Integer(RetCodeEnum.getRetCodeEnumByValue("ny",status).getDesc()));
							 result.setMessage(message);
							 repMap.put("orgCode", "NANYUN");
						}
					}
				} catch (Exception e) {
					repMap.put("nytype","0");
				}
			}
			repMap.put("orgName", orgName);
			repMap.put("status",status);
			repMap.put("message",message);
			repMap.put("custId",b.getCustId());
			repMap.put("orderNo", orderNo);//第三方返回的订单号，楠云不返回
			repMap.put("companyId", b.getCompanyId());
			repMap.put("bankName", b.getBankName());
			repMap.put("cardNumber", b.getCardNo());
			repMap.put("seq", b.getSeq());//自己生成的流水号
			//和第三方对接结束，进行数据修改
			customerCardService.updateBankBind(repMap);
		}else{
			result.setStatus(1);
			result.setMessage("系统错误，请联系客服！！！");
		}
		TBaseBanktype baseBankType = CacheUtil.getTBaseBanktype(orgName);
		TBaseBanktype banType = new TBaseBanktype();
		banType.setSubmitTime(DateUtil.dateFormat(DateUtil.dateFormat(new Date(),"yyyy-MM-dd"), "yyyy-MM-dd"));
		banType.setTypeId(b.getCardNo());
		result.setBody(banType);
		return result;
	}
	
	

}
